Delete Operation

Finally, you need to implement a route that allows users to delete existing transactions.

Complete the following steps to implement the Delete operation.

  1. Create a function named delete_transaction that takes a parameter, transaction_id.

  2. Decorate the function with @app.route and use the route string /delete/<int:transaction_id>. The <int:transaction_id> part in the URL is a placeholder for any integer. Flask will pass this integer to your function as the transaction_id argument.

  3. In the function body, find the transaction with the ID that matches transaction_id and remove it from the transactions list, then redirect the user back to the list of transactions.

Click here for solution
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  1. # Delete operation: Delete a transaction
  2. # Route to handle the deletion of an existing transaction
  3. @app.route("/delete/<int:transaction_id>")
  4. def delete_transaction(transaction_id):
  5. # Find the transaction with the matching ID and remove it from the list
  6. for transaction in transactions:
  7. if transaction['id'] == transaction_id:
  8. transactions.remove(transaction) # Remove the transaction from the transactions list
  9. break # Exit the loop once the transaction is found and removed
  10. # Redirect to the transactions list page after deleting the transaction
  11. return redirect(url_for("get_transactions"))

Now, the code will look like this:
Correct code reference